package com.yike.base.service.impl;

import com.yike.base.service.QrcodeService;
import com.yike.base.tool.QRCodeGenerator;
import com.yike.common.exception.BusinessException;
import lombok.extern.java.Log;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;

/**
 * @author Sakura
 * @date 2024/9/30 15:28
 */
@Service
@Log
public class QrcodeServiceImpl implements QrcodeService {

    @Value("${local.host}")
    String LOCAL_HOST;

    // 文件存放路径跟jar包同目录下/resources/files/
    private static final String LOCAL_FILE_PATH = "./resources/qrcode/";
    @Override
    public String generate(String text, String remark, Integer width, Integer height) throws Exception {
        // 随机生成一个文件名
        String code = RandomStringUtils.randomAlphanumeric(32);
        QRCodeGenerator.generateQRCode(text, remark, LOCAL_FILE_PATH + code + ".png", null, width, height);
        return LOCAL_HOST + "qrcode/" + code;
    }

    @Override
    public String generateWithLogo(MultipartFile file, String text, String remark, Integer width, Integer height) throws Exception {
        // 随机生成一个文件名
        String code = RandomStringUtils.randomAlphanumeric(32);

        // 创建临时文件，确保文件路径正确
        File convFile = File.createTempFile("logo_", "_" + file.getOriginalFilename());
        file.transferTo(convFile);

        // 调用生成二维码的方法
        QRCodeGenerator.generateQRCode(text, remark, LOCAL_FILE_PATH + code + ".png", convFile, width, height);

        // 删除临时文件
        convFile.delete();

        return LOCAL_HOST + "qrcode/" + code;
    }

    @Override
    public void download(HttpServletResponse response, String code) throws Exception {
        File downloadFile = new File(LOCAL_FILE_PATH + code + ".png");
        if (!downloadFile.exists() || downloadFile.length() == 0) {
            throw new BusinessException(500, "文件不存在");
        }

        // 确定文件的Content-Type
        String mimeType = Files.probeContentType(downloadFile.toPath());
        if (mimeType == null) {
            mimeType = "application/octet-stream"; // 默认类型
        }

        response.setContentType(mimeType);
        response.addHeader("Content-Length", String.valueOf(downloadFile.length()));
        response.addHeader("Content-Disposition", "attachment; filename=\"" + code + ".png\"");

        try (InputStream is = new FileInputStream(downloadFile);
             OutputStream os = response.getOutputStream()) {

            IOUtils.copy(is, os);
            os.flush(); // 确保数据已写入输出流
        } catch (IOException e) {
            log.info("下载图片发生IO异常");
            e.printStackTrace();
            throw new BusinessException(500, "文件下载失败");
        } catch (Exception e) {
            log.info("下载图片发生异常");
            e.printStackTrace();
            throw new BusinessException(500, "文件下载失败");
        }
    }
}
